package com.yfp.operation.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hy.corecode.idgen.WFGIdGenerator;
import com.yfp.common.core.constant.CacheConstants;
import com.yfp.common.core.domain.R;
import com.yfp.common.core.utils.bean.BeanUtils;
import com.yfp.common.datascope.annotation.DataScope;
import com.yfp.common.security.utils.SecurityUtils;
import com.yfp.operation.config.BajiushiProperties;
import com.yfp.operation.domain.*;
import com.yfp.operation.domain.dto.*;
import com.yfp.operation.domain.vo.*;
import com.yfp.operation.enums.CouponStatus;
import com.yfp.operation.enums.CouponTypeEnum;
import com.yfp.operation.mapper.*;
import com.yfp.operation.mapper.*;
import com.yfp.operation.service.MarCouponService;
import com.yfp.operation.service.MiniBannerService;
import com.yfp.operation.service.SysUserService;
import com.yfp.operation.utils.DateUtils;
import com.yfp.operation.domain.*;
import com.yfp.operation.domain.dto.*;
import com.yfp.operation.domain.vo.*;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.RedissonMultiLock;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.sql.Timestamp;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

/**
 *
 * @description 针对表【mar_coupon(优惠券)】的数据库操作Service实现
 * @createDate 2024-07-12 15:49:42
 */
@Service
@Slf4j
public class MarCouponServiceImpl extends ServiceImpl<MarCouponMapper, MarCoupon> implements MarCouponService {

    @Resource
    private MarCouponMapper marCouponMapper;
    @Resource
    private ClientCouponMapper clientCouponMapper;
    @Resource
    private OrderComboMapper orderComboMapper;
    @Resource
    private MarCouponComboMapper marCouponComboMapper;
    @Resource
    private MarCouponPositionMapper marCouponPositionMapper;
    @Resource
    private OrderListMapper orderListMapper;
    @Resource
    private MarketingMapper marketingMapper;
    @Resource
    private ClientMapper clientMapper;
    @Resource
    private WFGIdGenerator wfgIdGenerator;
    @Resource
    private MiniBannerService miniBannerService;
    @Resource
    private MarCouponExportMapper marCouponExportMapper;
    @Resource
    private RedissonClient redissonClient;
    @Resource
    private MarCouponDirectionalMapper marCouponDirectionalMapper;
    @Autowired
    private BajiushiProperties bajiushiProperties;
    @Resource
    private SysUserService sysUserService;


    /**
     * 新增优惠券
     *
     * @param marCoupon
     * @return
     */
    @Override
    @Transactional
    public R<Void> addMarCoupon(MarCoupon marCoupon) {
        // 创建人id
        marCoupon.setCreateUserId(SecurityUtils.getLoginUser().getSysUser().getUserId());
//        marCoupon.setCreateUserId(58L);
        // 创建默认状态为待开始  4
        marCoupon.setStatus(CouponStatus.FOUR.getStatus());

//        marCoupon.setId(wfgIdGenerator.next());
        if (null == marCoupon.getValidDays()) {
            long endTime = marCoupon.getValidEndTime().getTime();
            long startTime = marCoupon.getValidStartTime().getTime();
            long time1 = new Timestamp(System.currentTimeMillis()).getTime();
            if (time1 > endTime) {
                marCoupon.setStatus(CouponStatus.THREE.getStatus());
            } else if (time1 >= startTime && time1 <= endTime) {
                marCoupon.setStatus(CouponStatus.ONE.getStatus());
            }
        } else {
            marCoupon.setStatus(CouponStatus.ONE.getStatus());
        }
        marCoupon.setPostponeDay(0);
        long marketingId = wfgIdGenerator.next();
        // 剩余数量等于发放数量
        marCoupon.setSurplusCount(marCoupon.getCount());
        marCoupon.setMarketingId(marketingId);
        marCoupon.setDeptId(SecurityUtils.getLoginUser().getSysUser().getDeptId());

        // 实体券填充值
        if (marCoupon.getType().equals(CouponStatus.SIX.getStatus())) {
            marCoupon.setThreshold(BigDecimal.valueOf(0));
            marCoupon.setPosition(0);
            marCoupon.setClientStatus(1);
            marCoupon.setCombo(0);
            marCoupon.setCouponCentre(0);
            marCoupon.setSetting(0);
        }
        marCouponMapper.addMarCoupon(marCoupon);

        List<String> comboIdList = marCoupon.getComboIdList();
        if (!comboIdList.isEmpty()) {
            marCouponComboMapper.add(marCoupon.getId(), comboIdList);
        }

        List<String> positionIdList = marCoupon.getPositionIdList();
        if (!positionIdList.isEmpty()) {
            marCouponPositionMapper.add(marCoupon.getId(), positionIdList);
        }



        Integer status = 1;
        Marketing marketing = new Marketing();
        marketing.setType(status);
        marketing.setMarCouponId(marCoupon.getId());
        marketing.setId(marketingId);
        marketingMapper.add(marketing);

        // 判断是否弹窗，如果弹窗则需要将之前的弹窗banner覆盖
        if (marCoupon.getPopup().equals(CouponStatus.ONE.getStatus())) {
            MiniBanner miniBanner = new MiniBanner();
            miniBanner.setName(marCoupon.getCouponName());
            miniBanner.setImg(marCoupon.getPopupUrl());
            miniBanner.setPosition(3);
            miniBanner.setMarketingId(marketing.getId());
            miniBanner.setRemark("添加券时加入");
            miniBanner.setCityName(marCoupon.getCityName());
            miniBanner.setDeptId(marCoupon.getDeptId());
            miniBannerService.createMiniBannerPopup(miniBanner);
        }

        return R.ok();
    }


    /**
     * 多条件获取优惠券列表
     *
     * @param couponQueueDTO
     * @return
     */
    @Override
    @DataScope(deptAlias = "mc")
    public List<MarCouponVO> selectMarCoupon(CouponQueueDTO couponQueueDTO) {
        List<MarCouponVO> marCouponList = marCouponMapper.selectMarCoupon(couponQueueDTO);
        return marCouponList;
    }

    /**
     * 活动列表数据补全
     *
     * @param marCouponList
     * @return
     */
    @Override
    public List<MarCouponVO> complementListData(List<MarCouponVO> marCouponList) {
        // 获取优惠券id
        List<Long> couponIds = marCouponList.stream().map(MarCouponVO -> MarCouponVO.getId()).collect(Collectors.toList());

        // 根据优惠券id和状态获取该优惠券使用情况
        List<CouponCountVO> countVOS = clientCouponMapper.getCount(couponIds);
        Map<Long, CouponCountVO> countVOMap = countVOS.stream().collect(Collectors.toMap(CouponCountVO::getCouponId, Function.identity()));

        for (MarCouponVO marCouponVO : marCouponList) {
            Long couponId = marCouponVO.getId();
            if (countVOMap.containsKey(couponId)) {
                CouponCountVO couponCountVO = countVOMap.get(couponId);
                marCouponVO.setNeckNum(couponCountVO.getDrawCount());
                marCouponVO.setUseNum(couponCountVO.getUseCount());
            }
        }
        return marCouponList;
    }

    /**
     * 套餐列表-数据API
     *
     * @param couponId
     * @return
     */
    @Override
    @Transactional
    public R<MarCouponDataVO> getMarCouponData(Long couponId) {

        if (couponId == null) {
            return R.fail("参数不足");
        }

        List<Long> couponIds = new ArrayList<>();
        couponIds.add(couponId);

        List<CouponDetailVO> detailVOList = clientCouponMapper.detail(couponIds);
        // 根据优惠券id获取领取该优惠券的用户id
        List<String> clientIds = clientCouponMapper.getClientId(couponId, CouponStatus.TWO.getStatus());

        // 获取用户领取该优惠券的第一下单时间
        List<UseQueueVO> useQueueVOS = orderComboMapper.getBuyTime(couponId);

        // 老用户用券数量
        Integer num = 0;
        if (!useQueueVOS.isEmpty()) {
            for (UseQueueVO useQueueVO : useQueueVOS) {
                // 查询是否存在该时间之前的订单
                Integer count = orderComboMapper.historyOrder(useQueueVO);
                if (count > 0) {
                    num++;
                }
            }
        }

        MarCouponDataVO marCouponDataVO = new MarCouponDataVO();
        marCouponDataVO.setFormerCount(num);
        marCouponDataVO.setNewnessCount(0);
        marCouponDataVO.setTurnover(new BigDecimal(0));
        marCouponDataVO.setUnitPrice(new BigDecimal(0));
        marCouponDataVO.setDiscounts(new BigDecimal(0));
        if (!clientIds.isEmpty()) {
            int size = clientIds.size();
            marCouponDataVO.setNewnessCount(size - num);
        }

        if (!detailVOList.isEmpty()) {
            CouponDetailVO couponDetailVO = detailVOList.get(0);
            marCouponDataVO.setTurnover(couponDetailVO.getTurnover());
            marCouponDataVO.setDiscounts(couponDetailVO.getDiscounts());
            BigDecimal unitPrice = couponDetailVO.getTurnover().divide(new BigDecimal(couponDetailVO.getNum()), 2, RoundingMode.HALF_UP);
            marCouponDataVO.setUnitPrice(unitPrice);
        }

        marCouponDataVO.setPurchaseCount(0);
        Integer comboNum = orderListMapper.getComboNum(couponId);
        if (comboNum != null) {
            marCouponDataVO.setPurchaseCount(comboNum);
        }
        return R.ok(marCouponDataVO);
    }

    /**
     * 删除活动
     *
     * @param couponId
     */
    @Override
    @Transactional
    public void deleteMarCoupon(Long couponId, Integer status) {
        log.info("修改优惠券:{},状态:{}", couponId, status);

        Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
//        Long userId = 58L;

        // 修改活动状态
        marCouponMapper.updateStatus(couponId, status, userId);

        // 将领取的优惠券状态改成失效
        clientCouponMapper.invalidByCouponId(couponId, CouponStatus.ZERO.getStatus());
    }


    /**
     * 领取优惠券列表
     *
     * @param acquireCouponDTO
     * @return
     */
    @Override
    public List<AcquireListVO> acquireCouponList(AcquireCouponDTO acquireCouponDTO) {
        List<AcquireListVO> list = clientCouponMapper.acquireCouponList(acquireCouponDTO);
        return list;
    }

    @Override
    public List<AcquireListVO> acquireCouponListomplement(List<AcquireListVO> list, AcquireCouponDTO acquireCouponDTO) {
        if (CollUtil.isEmpty(list)) {
            return list;
        }
        // 填充实物券核销人Name
        List<AcquireListVO> list1 = list.stream().peek(item -> {
            if (CouponTypeEnum.PHYSICAL_PRODUCT.getCode().equals(item.getType())){
                if (Objects.nonNull(item.getVerifyUserId())) {
                    SysUser sysUser = sysUserService.getById(item.getVerifyUserId());
                    item.setVerifyUserName(sysUser.getNickName());
                }
                if (Objects.nonNull(item.getVerifyTime())) {
                    item.setUseTime(DateUtil.format(item.getVerifyTime(), DatePattern.NORM_DATETIME_PATTERN));
                }
            }
        }).filter(item -> {
            if (StrUtil.isNotBlank(acquireCouponDTO.getVerifyUserName())) {
                return StrUtil.contains(item.getVerifyUserName(), acquireCouponDTO.getVerifyUserName());
            }
            return true;
        }).toList();
        return list1;
    }

    @Override
    @DataScope(deptAlias = "mc")
    public R<List<MarCouponVO>> groupCouponList(GroupCouponListDTO groupCouponListDTO) {
        List<MarCouponVO> marCouponList = marCouponMapper.groupCouponList(groupCouponListDTO);
        return R.ok(marCouponList);
    }


    /**
     * 根据标签和城市名获取优惠券
     * @return
     */
    @Override
    public List<MarCouponVO> getByPositionAndCityName(GroupCouponListDTO groupCouponListDTO) {
        return marCouponMapper.getByPositionAndCityName(groupCouponListDTO);
    }


    /**
     * 发放优惠券
     *
     * @param couponIds
     */
    @Override
    @Transactional
    public R<List<GrantDetailVO>> grant(List<Long> couponIds) {
        List<String> lockKeys = couponIds.stream().map(item -> CacheConstants.MAR_COUPON_SURPLUSCOUNT_LOCK_KEY + item).collect(Collectors.toList());
        List<RLock> rLocks = lockKeys.stream().map(lockKey -> {
            RLock lock = redissonClient.getLock(lockKey);
            return lock;
        }).collect(Collectors.toList());
        RedissonMultiLock redissonMultiLock = new RedissonMultiLock(rLocks.toArray(new RLock[rLocks.size()]));
        Assert.isTrue(redissonMultiLock.tryLock(), "稍后重试");

        try {
            List<GrantDetailVO> grantDetailVOS = new ArrayList<>();
            for (Long couponId : couponIds) {
                GrantDetailVO grantDetailVO = new GrantDetailVO();
                Integer count = 0;
                // 查询优惠券信息
                MarCoupon marCoupon = marCouponMapper.selectById(couponId);
                if (marCoupon == null) {
                    log.info("优惠券信息为空,优惠券id:{}", couponId);
                    grantDetailVO.setCount(count);
                    grantDetailVOS.add(grantDetailVO);
                    continue;
                }
                grantDetailVO.setName(marCoupon.getCouponName());

                if (marCoupon.getStatus().equals(CouponStatus.THREE.getStatus())) {
                    grantDetailVO.setCount(count);
                    grantDetailVOS.add(grantDetailVO);
                    continue;
                }

                // 获取剩余数量
                Integer surplusCount = marCoupon.getSurplusCount();

                Integer clientStatus = marCoupon.getClientStatus();

                // 获取所有用户id
                List<String> clientIds = clientMapper.selectByCityName(marCoupon.getCityName());

                if (clientIds.isEmpty()) {
                    grantDetailVO.setCount(count);
                    grantDetailVOS.add(grantDetailVO);
                    continue;
                }

                List<String> list = new ArrayList<>(clientIds);
                // 分片  2000 一查
                int splitSize = 2000;
                List<List<String>> splitLists1 =
                        IntStream.range(0, (list.size() + splitSize - 1) / splitSize)
                                .mapToObj(i -> list.subList(i * splitSize, Math.min(list.size(), (i + 1) * splitSize)))
                                .collect(Collectors.toList());

                for (List<String> splitList : splitLists1) {
                    // 获取优惠券数量大于可领取数量的用户   即不能领取的id
                    List<String> clientIdList = clientCouponMapper.clientId(splitList, marCoupon.getReceiveCount(), couponId);

                    if (!clientIdList.isEmpty()) {
                        clientIds.removeAll(clientIdList);
                    }
                }

                ClientCoupon clientCoupon = new ClientCoupon();

                if (null != marCoupon.getValidDays()) {
                    // 当前日期
                    LocalDate currentDate = LocalDate.now();
                    // 要添加的天数
                    int daysToAdd = marCoupon.getValidDays();
                    // 当前日期加上指定天数
                    LocalDate newDate = currentDate.plusDays(daysToAdd);
                    // 获取结果日期的起始时间（00:00:00）
                    LocalDateTime startOfDay = newDate.atStartOfDay();
                    LocalDateTime localDateTime = startOfDay.minusSeconds(1);
                    // 转换为Instant
                    Instant instant = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
                    // 转换为Timestamp
                    Timestamp timestamp = Timestamp.from(instant);
                    marCoupon.setValidStartTime(new Timestamp(System.currentTimeMillis()));
                    marCoupon.setValidEndTime(timestamp);
                }

                BeanUtils.copyBeanProp(clientCoupon, marCoupon);
                clientCoupon.setStatus(marCoupon.getStatus());
                clientCoupon.setCouponId(couponId.longValue());
                clientCoupon.setPostponeDay(0);


                // 全部用户
                if (clientStatus == CouponStatus.ONE.getStatus()) {
                    clientIds = clientIds.stream().limit(surplusCount).toList();
                    // 新用户
                } else if (clientStatus == CouponStatus.TWO.getStatus()) {
                    // 老用户ID
                    List<String> odrUserIds = orderComboMapper.agedClientId();
                    // 新用户ID，过滤老用户
                    clientIds = clientIds.stream().filter(userId -> !odrUserIds.contains(userId)).toList();
                }

                // 发放用户id
                List<String> userIds = new ArrayList<>(clientIds);

                // 分片  2000 一发
                List<List<String>> splitLists =
                        IntStream.range(0, (userIds.size() + splitSize - 1) / splitSize)
                                .mapToObj(i -> userIds.subList(i * splitSize, Math.min(userIds.size(), (i + 1) * splitSize)))
                                .collect(Collectors.toList());

                for (List<String> splitList : splitLists) {
                    clientCouponMapper.grant(splitList, clientCoupon);
                }

                count = userIds.size();

                // 修改剩余数
                marCoupon.setSurplusCount(surplusCount - count);
                marCouponMapper.updateSurplusCount(couponId, marCoupon.getSurplusCount());
                grantDetailVO.setCount(count);
                grantDetailVOS.add(grantDetailVO);
            }
            return R.ok(grantDetailVOS);
        } finally {
            redissonMultiLock.unlock();
        }
    }

    /**
     * 根据优惠券id获取数据
     *
     * @param couponId
     * @return
     */
    @Override
    public MarCoupon selectById(Long couponId) {
        MarCoupon marCoupon = marCouponMapper.selectById(couponId);


        // 套餐列表
        List<MarCouponCombo> marCouponCombos = marCouponComboMapper.selectByMarCouponId(couponId.longValue());
        if (!marCouponCombos.isEmpty()) {
            List<String> comboIdList = marCouponCombos.stream().map(marCouponCombo -> marCouponCombo.getComboId()).collect(Collectors.toList());
            marCoupon.setComboIdList(comboIdList);
        }

        // 全部点位的不查
        if (marCoupon.getPosition() != 0 && marCoupon.getPosition() != 2) {
            // 点位列表
            List<MarCouponPosition> marCouponPositions = marCouponPositionMapper.selectByMarCouponId(couponId.longValue());
            if (!marCouponPositions.isEmpty()) {
                List<String> positionIdList = marCouponPositions.stream().map(marCouponPosition -> marCouponPosition.getPositionId()).collect(Collectors.toList());
                marCoupon.setPositionIdList(positionIdList);
            }
        }

//        marCoupon.setPosition(marCoupon.getLabel());
        return marCoupon;
    }


    /**
     * 进行中优惠券列表
     *
     * @param couponQueueDTO
     * @return
     */
    @Override
    @DataScope(deptAlias = "mc")
    public R<List<MarCouponVO>> getByTypeMarCoupon(CouponQueueDTO couponQueueDTO) {
        List<MarCouponVO> marCouponList = marCouponMapper.selectMarCoupon(couponQueueDTO);
        return R.ok(marCouponList);
    }

    /**
     * 延长时间
     *
     * @param lengthenDateDTO
     */
    @Override
    @Transactional
    public void lengthen(LengthenDateDTO lengthenDateDTO) {
        List<Long> couponIds = lengthenDateDTO.getCouponIds();
        Integer dayNumber = lengthenDateDTO.getDayNumber();
        if (couponIds.isEmpty() || dayNumber == null) {
            return;
        }
        List<MarCoupon> list = marCouponMapper.getMarCoupon(couponIds);
        if (!list.isEmpty()) {
            for (MarCoupon marCoupon : list) {
                Integer postponeDay = marCoupon.getPostponeDay();
                marCoupon.setPostponeDay(postponeDay + dayNumber);

                Timestamp validEndTime = marCoupon.getValidEndTime();

                Timestamp timestamp1 = DateUtils.addDay(validEndTime, marCoupon.getPostponeDay());
                if (timestamp1.getTime() > System.currentTimeMillis()) {
                    marCoupon.setStatus(CouponStatus.ONE.getStatus());
                }
            }
            marCouponMapper.lengthen(list);
            clientCouponMapper.lengthen(list);
        }
    }

    @Override
    public void exportLengthen(LengthenDateDTO lengthenDateDTO) {
        List<MarCouponExport> marCouponExports = marCouponExportMapper.selectBatchIds(lengthenDateDTO.getExportIds());
        for (MarCouponExport marCouponExport : marCouponExports) {
            ClientCoupon clientCoupon = clientCouponMapper.selectById(marCouponExport.getClientCouponId());
            if (null != clientCoupon) {
                clientCoupon.setValidEndTime(DateUtils.addDay(clientCoupon.getValidEndTime(), lengthenDateDTO.getDayNumber()));
                clientCouponMapper.updateById(clientCoupon);
            }
        }
    }


    /**
     * 导出
     *
     * @param couponDeriveDTO
     */
    @Override
    @Transactional
    public List<String> derive(CouponDeriveDTO couponDeriveDTO) {
        RLock lock = redissonClient.getLock(CacheConstants.MAR_COUPON_SURPLUSCOUNT_LOCK_KEY + couponDeriveDTO.getMarCouponId());
        Assert.isTrue(lock.tryLock(), "稍后重试");
        try {
            Long userId = SecurityUtils.getLoginUser().getSysUser().getUserId();
//             Long userId = 58L;

            // 优惠券id
            Long marCouponId = couponDeriveDTO.getMarCouponId();
            MarCoupon marCoupon = marCouponMapper.selectById(marCouponId);
            if (marCoupon == null) {
                return new ArrayList<>();
            }
            // 导出数量
            Integer count = couponDeriveDTO.getCount();

            // 获取当前日期
            LocalDate currentDate = LocalDate.now();
            // 定义日期格式化器
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
            // 格式化日期为字符串
            String dateTime = currentDate.format(formatter);

            // 获取今天该优惠券导出列表的最后一条的数字
            Integer endNum = marCouponExportMapper.endNum(dateTime);
            if (endNum == null) {
                endNum = 0;
            }

            // 最大导出数量
            int num = 99999 - endNum;

            // 如果最大导出数量小于需要导出的数量， 则将导出数量覆盖
            if (num < count) {
                count = num;
            }

            // 剩余数量判断
            Assert.isFalse(marCoupon.getSurplusCount() < count, "优惠券剩余数量不足");

            List<String> ids = new ArrayList<>();
            List<MarCouponExport> list = new ArrayList<>();
            Integer s = 0;
            for (int i = endNum + 1; i <= (count + endNum); i++) {
                MarCouponExport marCouponExport = new MarCouponExport();
                marCouponExport.setMarCouponId(marCouponId);
                marCouponExport.setCreateUserId(userId);
                marCouponExport.setStatus(CouponStatus.ZERO.getStatus());
                String paddedNumber = String.format("%05d", i);
                marCouponExport.setId("EXP-" + dateTime + "-" + paddedNumber);
                ids.add(bajiushiProperties.getDomain() + "/openappmy?exportId=" + marCouponExport.getId());
                list.add(marCouponExport);
                s++;
                if (s == 2000) {
                    marCouponExportMapper.add(list);
                    s = 0;
                    list.clear();
                }
            }

            if (!list.isEmpty()) {
                marCouponExportMapper.add(list);
            }

            LambdaUpdateWrapper<MarCoupon> wrapper = new LambdaUpdateWrapper<MarCoupon>().set(MarCoupon::getSurplusCount, marCoupon.getSurplusCount() - count).eq(MarCoupon::getId, marCouponId);
            marCouponMapper.update(null, wrapper);

            return ids;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            lock.unlock();
        }
    }


    /**
     * 导出详情
     *
     * @param acquireCouponDTO
     * @return
     */
    @Override
    public List<DeriveDetailVO> deriveDetail(AcquireCouponDTO acquireCouponDTO) {

        Integer status = acquireCouponDTO.getStatus();
        if (status != null && status == 8) {
            acquireCouponDTO.setStatus(null);
            acquireCouponDTO.setReceiveStatus(CouponStatus.ZERO.getStatus());
        }

        List<DeriveDetailVO> list = clientCouponMapper.deriveDetail(acquireCouponDTO);
        return list;
    }

    /**
     * 设置小程序广告
     *
     * @param id
     * @param popupUrl
     */
    @Override
    public void setMiniBannerPopup(Long id, String popupUrl) {
        LambdaUpdateWrapper<MarCoupon> eq = Wrappers.lambdaUpdate(MarCoupon.class).set(MarCoupon::getPopup, 1).set(MarCoupon::getPopupUrl, popupUrl).eq(MarCoupon::getId, id);
        this.update(eq);
    }

    /**
     * 导出列表失效
     *
     * @param checkId
     */
    @Override
    @Transactional
    public void invalid(String checkId) {
        if (checkId == null || checkId.equals("")) {
            return;
        }
        // 修改导出表的状态
        marCouponExportMapper.invalid(checkId, CouponStatus.TWO.getStatus());

        MarCouponExport marCouponExport = marCouponExportMapper.selectById(checkId);

        // 如果该纸质券被领取了，则修改领取表的状态
        if (marCouponExport.getClientCouponId() != null) {
            clientCouponMapper.invalid(marCouponExport.getClientCouponId(), CouponStatus.ZERO.getStatus());
        }
    }

    @Override
    public void callUpdateMarCouponStatus() {
        marCouponMapper.callUpdateMarCouponStatus();
    }


    /**
     * 领取列表失效
     *
     * @param clientCouponId
     */
    @Override
    public void inviteinvalid(Long clientCouponId) {
        if (clientCouponId == null) {
            return;
        }
        clientCouponMapper.invalid(clientCouponId, CouponStatus.ZERO.getStatus());

        marCouponExportMapper.inviteinvalid(clientCouponId, CouponStatus.TWO.getStatus());
    }

    @Override
    public Boolean checkComboParticipation(String comboId) {
        Long count = marCouponMapper.checkComboParticipation(comboId);
        return count > 0;
    }


    /**
     * 设置弹窗图
     *
     * @param img
     * @param marCouponId
     */
    @Override
    public void updatePopupUrl(String img, Long marCouponId) {
        marCouponMapper.updatePopupUrl(img, marCouponId);
    }

    @Override
    @DataScope(deptAlias = "mc")
    public List<MarCoupon> listByPackCouponReq(MarCouponPackCouponReqDTO marCouponPackCouponReqDTO) {
        return marCouponMapper.listByPackCouponReq(marCouponPackCouponReqDTO);
    }

    /**
     * 抽奖奖励列表
     *
     * @param prizeVO
     * @return
     */
    @Override
    @DataScope(deptAlias = "mc,mcp")
    public List<PrizeVO> prizeList(PrizeVO prizeVO) {

        List<PrizeVO> prizeVOS = marCouponMapper.prizeList(prizeVO);

        for (PrizeVO pv : prizeVOS) {
            pv.setStartTime(new Timestamp(System.currentTimeMillis()));
            if (null != pv.getValidDays()) {
                // 当前日期
                LocalDate currentDate = LocalDate.now();
                // 要添加的天数
                int daysToAdd = pv.getValidDays();
                // 当前日期加上指定天数
                LocalDate newDate = currentDate.plusDays(daysToAdd);
                // 获取结果日期的起始时间（00:00:00）
                LocalDateTime startDay = newDate.atStartOfDay();
                LocalDateTime localDateTime = startDay.minusSeconds(1);
                // 转换为Instant
                Instant ins = localDateTime.atZone(ZoneId.systemDefault()).toInstant();
                // 转换为Timestamp
                Timestamp timestamp = Timestamp.from(ins);
                pv.setEndTime(timestamp);
            }
        }
        return prizeVOS;
    }

    @Override
    public void disable(Long couponId) {
        marCouponMapper.disable(couponId);
    }


    /**
     * 全国优惠券
     *
     * @param nationwideCouponDTO
     * @return
     */
    @Override
    @DataScope(deptAlias = "mc")
    public List<MarCoupon> nationwideCoupon(NationwideCouponDTO nationwideCouponDTO) {
        return marCouponMapper.nationwideCoupon(nationwideCouponDTO);
    }

    @Override
    public void updateSurplusCount(Long id, int i) {
        marCouponMapper.updateSurplusCount(id, i);
    }


}




